﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SLS.ExClassLib.Events;
/*
 * 创建新纪录时，首先根据模板查询，然后将值传入新纪录
 */
namespace LanSunERP
{

    public partial class SQLFunction
    { 
        public DataSet QueryAndCreateTable(DataRow dwQueryCond, bool ModelReturn = false, bool blSave = true)
        {
            DataSet setReturn = new DataSet();
            dwForeignKeyList = null;
            string QueryType, CONDTYPE, BaseTable, TBName;
            try
            {
                if (dwQueryCond == null)
                {
                    dwQueryCond = dwRequest;
                }

                QueryType = dwQueryCond["QUERYTYPE"].ToString().Trim();
                CONDTYPE = dwQueryCond["CONDTYPE"].ToString().Trim();
                TBName = dwQueryCond.Table.TableName;
                if (CONDTYPE.Contains("QueryCond"))
                {
                    BaseTable = TBName; 
                    myConnection = LanSunERPQueryCondCon;                    
                }
                else
                {
                    myConnection = LanSunERPCon;
                    BaseTable = TBName.Replace("QueryCond", "");
                }
                DataRow dwBaseRecord = MapDataRow("", "", BaseTable, dwQueryCond, null, null, true);
                dwBaseRecord["SM"] = dwQueryCond["SM"];
                dwForeignKeyLists = TBForeignKeyList.Select("TBNAME='" + BaseTable + "' and FOREIGNKEY='" + CONDTYPE + "'");
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKeyList = dwForeignKeyLists[0];
                }
                else
                {
                    Tracer.Verbose("QueryAndCreateTable: ForeignKey does not exist. CONDTYPE:" + CONDTYPE + " of Table:" + BaseTable, dwBaseRecord);
                    return setReturn;
                }
                //Tracer.Verbose("QueryAndCreateTable: StartQuery", dwBaseRecord);
                setReturn = this.BuildAndRunCmdSQL(dwBaseRecord, dwForeignKeyList);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private DataSet CreateNewRecord(DataRow dwTarget, DataTable tableExists, bool ModelReturn = false, bool blSave = true)
        {
            //dwTarget=dwGoodsType;
            DataSet setTarget = new DataSet();
            DataSet setModel = new DataSet();
            string XKey = "";
            string TKey = "";
            string QueryType = "QueryOnly";
            string TBName = dwTarget.Table.TableName;
            Queue PrimaryKeyList = new Queue();
            Queue ForeignKeyList = new Queue();
            Queue MPrimaryKeyList = new Queue();
            Queue MForeignKeyList = new Queue();
            PrimaryKeyList = new Queue();
            ForeignKeyList = new Queue();
            try
            {
                #region QueryCond
                dwForeignKeyLists = TBForeignKeyList.Select("TBNAME='" + TBName + "' and TYPE='Model'");
                dwForeignKeyList = null;
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKeyList = dwForeignKeyLists[0];
                }
                string TForeignKey = dwForeignKeyList["TFOREIGNKEY"].ToString().Trim();
                string TargetTableQueryCond = dwForeignKeyList["TARGETTABLE"].ToString().Trim() + "QueryCond";
                for (int i = 0; i <= 9; i++)
                {
                    XKey = dwForeignKeyList["KEY" + i.ToString()].ToString().Trim();
                    TKey = dwForeignKeyList["TKEY" + i.ToString()].ToString().Trim();
                    if (XKey != "")
                    {
                        PrimaryKeyList.Enqueue(XKey);
                        MPrimaryKeyList.Enqueue(XKey);
                        ForeignKeyList.Enqueue(TKey);
                        MForeignKeyList.Enqueue(TKey);
                    }
                }
                #endregion
                DataRow dwMainKeyDefQueryCond =
                PrepareQueryCond(QueryType, TForeignKey, TargetTableQueryCond, dwTarget, ForeignKeyList, PrimaryKeyList);
                setModel = new DataSet();
                setModel = QueryAndCreateTable(dwMainKeyDefQueryCond);
                setTarget = new DataSet(); 
                #region SKREALExist
                /*
                    foreach (DataRow dwExist in dtExists.Rows)
                    {
                
                        if (TBExist == "GoodsMasterProperty")
                        {
                            string SKREALExist = dwExist["SKREAL"].ToString().Trim();
                            foreach (DataRow dwTemp in setModel.Tables[0].Rows)
                            {
                                if (dwTemp.Table.TBNAME == "GoodsTypePropertyDef")
                                {
                                    SKREAL = dwTemp["SKREAL"].ToString().Trim();
                                }
                                if (SKREAL == SKREALExist)
                                {
                                    dwTemp.Delete();
                                }
                            }
                        }
                    }
                  
                    setModel.AcceptChanges();
                        *   */
                #endregion
                setTarget = HandleModelData(dwTarget, setModel, MForeignKeyList, MPrimaryKeyList, blSave);
                if (ModelReturn)
                {
                    setTarget = ImportDataTable(setTarget, setModel.Tables[0]);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            #region Including the model information
            /*
            foreach (DataTable dtTmp in setModel.Tables)
            {
                setTarget = ImportDataTable(setTarget, dtTmp);
            }
            */
            #endregion
            return setTarget;
        }
        public virtual DataSet HandleModelData(DataRow dwReference, DataSet setModel, Queue ForeignKeyList, Queue PrimaryKeyList, bool blSave = true)
        {
            DataSet setGoods = null, setResult = null;
            DataRow rowTarget;
            DataSet setReturn = new DataSet();
            DataSet setMiddle = new DataSet();
            string TBNAME = dwReference.Table.TableName;
            List<string> ForeignKey = new List<string>();
            List<string> PrimaryKey = new List<string>();
            string PropertyName = "";
            if (setModel.Tables[0].Rows.Count == 0)
            {
                Tracer.Info(logRoute, "setModel");
                return setReturn;
            }
            try
            {
                while (ForeignKeyList.Count > 0)
                {
                    ForeignKey.Add(ForeignKeyList.Dequeue().ToString());
                }
                while (PrimaryKeyList.Count > 0)
                {
                    PrimaryKey.Add(PrimaryKeyList.Dequeue().ToString());
                }
                foreach (DataRow dwModel in setModel.Tables[0].Rows)
                {
                    #region  MapModel to instance
                    //1st, 保留UI 传递过来的信息，一般是主键信息
                    rowTarget = MapDataRow("", "", TBNAME, dwReference, null, null, false);
                    //2.根据指定的字段，将主键字段进一步扩展填充
                    //这两个合并
                    rowTarget = MapDataRow("", "", rowTarget, dwReference, ForeignKey, PrimaryKey, false);
                    //dwTarget = MapDataRow("", "", dwTarget, dwReference, ForeignKey, PrimaryKey, false);
                    //3.根据相同列表，将模板数据进行映射。
                    rowTarget = MapDataRow("", "", rowTarget, dwModel, null, null, true);
                    if (TBNAME == "GoodsMasterProperty")
                    {
                        PropertyName = dwModel["PROPERTYNAME"].ToString().Trim();
                        if (PropertyName == "PredefinedSGTKEY")
                        {
                            rowTarget["SKREAL"] = dwReference["SKREAL"];
                            rowTarget["SKEYDEFTYPE"] = dwReference["SKEYDEFTYPE"];
                            rowTarget["SGTPRE"] = dwReference["SGTPRE"];
                            rowTarget["SGTKEY"] = dwReference["SGTKEY"];
                        }
                    }
                    #endregion
                    rowTarget = UpdateLastPOS(rowTarget, dwModel);
                    rowTarget["UID"] = Guid.NewGuid().ToString().ToUpper();
                    #region GoodsMasterAssemblePoint
                    if (TBNAME == "GoodsMasterAssemblePoint")
                    {
                        setGoods = AutoMaterialKeyGeneration(rowTarget, dwModel);
                        if (setGoods != null)
                        {
                            setMiddle.Merge(setGoods);
                        }
                    }
                    #endregion

                    #region MultiSlaveKeyGoodsMasterKeyRelation
                    else
                    {
                        setResult = MultiSlaveKeyGoodsMasterKeyRelation(rowTarget);
                        if (setResult != null)
                        {
                            setMiddle.Merge(setResult);
                        }
                        else
                        {
                            setMiddle = this.ImportDataTable(setMiddle, rowTarget);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            if (blSave)
            {
                setResult = SaveRecord(setMiddle, false);
                setReturn = setResult;
            }
            else
            {
                setReturn = setMiddle;
            }
            return setReturn;
        }
    }
}